package cn.whao.guli.gateway.filter;

import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.util.AntPathMatcher;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

/**
 * ClassName: MyPathGlobalFilter
 * Package: cn.whao.guli.gateway.filter
 * Description: 自定义网关全局过滤器
 *
 * @Author 王豪
 * @Create 2024/11/28 19:37
 * @Version 1.0
 */
@Component
public class MyPathGlobalFilter implements GlobalFilter, Ordered {

    /**
     * @param exchange 交换机，可以获取请求对象和响应对象
     * @param chain    filter链，可以放行请求给下一个过滤器或目标服务
     * @return
     */
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        ServerHttpRequest request = exchange.getRequest();
        ServerHttpResponse response = exchange.getResponse();
        // 获取请求路径，如果包含 /stock，则拦截请求，否则放行
        String path = request.getURI().getPath();
        AntPathMatcher antPathMatcher = new AntPathMatcher();
        if (antPathMatcher.match("/stock/**", path)) {
            // 拦截请求，响应拦截提示
            response.setStatusCode(HttpStatus.OK); // 响应状态码
            response.getHeaders().set(HttpHeaders.CONTENT_TYPE, "text/html;charset=UTF-8"); // 设置响应头
            // 设置响应体
            DataBuffer buffer = response.bufferFactory().wrap("访问失败，请联系管理员解决！".getBytes());
            return response.writeWith(Mono.just(buffer));
        }
        // 放行请求
        return chain.filter(exchange);
    }

    /**
     * 获取过滤器的执行顺序，值越小，优先级越高
     * @return
     */
    @Override
    public int getOrder() {
        return 0;
    }
}
